<template>
  <div class="history">
      <h2>历史记录<van-icon name="delete-o" @click="clearHistory" /></h2>
      
      <div class="history-list">
          <van-tag color="#666" @click="hisSearch(h.title)" plain v-for="(h,index) in hisList" :key="index">{{h.title}}</van-tag>
      </div>
  </div>
</template>

<script>
    import { Toast } from 'vant'
    export default {
        name:'History',
        data() {
            return {
                hisList:JSON.parse(localStorage.getItem('history'))||[],
            }
        },
        methods: {
            clearHistory(){
                this.hisList=[]
                Toast.success('清空成功');
            },
            hisSearch(title){
                this.$bus.$emit('addSearch',title);
            },
            addHistory(val){
                this.hisList.unshift({title:val});
            }
        },mounted() {
            this.$bus.$on('addHistory',this.addHistory);
        },
        beforeDestroy() {
            this.$bus.$off('addHistory');
        },
        watch: {
            hisList:{
                deep:true,
                handler(value){
                    window.localStorage.setItem("history",JSON.stringify(value));
                }
            }
        },
    }
</script>

<style  scoped >
    h2{
        padding: 10px;
        margin: 0;
        text-align: left;
        margin-left: 20px;
    }
    h2>i{
        font-size: 20px;
        float:right;
        margin-right: 5px;
    }
    .history{
        width: 100%;
        background-color: white;
    }
    .history-list{
        text-align: left;
        margin-left: 20px;
    }
    .history-list>span{
        margin: 5px;
    }
</style>